package 实验四2;

class SharedResource {
    private int sharedValue = 0;

    public synchronized void increment() {
        sharedValue++;
    }

    public synchronized void printValue() {
        System.out.println("Shared Value: " + sharedValue);
    }
}

public class Main {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        // 线程1：多次调用increment()
        Thread incrementThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.increment();
                try {
                    Thread.sleep(100); // 模拟操作耗时
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 线程2：多次调用printValue()
        Thread printThread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                resource.printValue();
                try {
                    Thread.sleep(100); // 保持与incrementThread同步
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 启动线程
        incrementThread.start();
        printThread.start();

        // 等待两个线程执行完毕
        try {
            incrementThread.join();
            printThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
